package ru.osu.acm.common.industrial;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * User: aleksey
 * Date: Sep 22, 2009
 * Time: 10:34:17 AM
 */
public class Factory {
    protected static void closeConnection(Connection con, boolean reallyClose) {
        if (reallyClose) {
            try {
                con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected static int getNextId(String table, Connection con, boolean closeConnection) {
        int newId = 1;

        try {
            PreparedStatement statement = con.prepareStatement("select id from " + table + " order by id desc limit 1");
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                newId = resultSet.getInt("id") + 1;
            }
            resultSet.close();
            statement.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        closeConnection(con, closeConnection);
        return newId;
    }
}
